// src/app.tsx
import React from 'react';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { getSystemInfo, getUserAvatar, getSystemLogo} from '@/services/main/index';
import { errorConfig } from './requestErrorConfig';
import {  notification } from 'antd';
import { getAccessToken, setSessionToken,getRefreshToken, getTokenExpireTime, clearSessionToken } from '@/access';
import { PageEnum } from './enums/pagesEnums';
import CustomLayout from '@/layouts/CustomLayout';
import { normalizePath } from '@/utils/path';
import { getActiveTabKey, getTabState,cleanupExpiredTabStates } from '@/utils/tabPersistence';
import '@/assets/styles/iconfont.css';

const isDev = process.env.NODE_ENV === 'development';
const LOGIN_PATH = PageEnum.LOGIN;

// 菜单项类型定义
interface MenuItem {
  menuId: number;
  name: string;
  path: string;
  children?: MenuItem[] | null;
}

// 缓存键常量
const CACHE_KEYS = {
    MENU: 'menu-cache',
    AVATAR: 'avatar-base64',
    LOGO: 'logo-base64',
    AVATAR_ETAG: 'avatar-etag',
    LOGO_ETAG: 'logo-etag'
};
  
// 生成并缓存 Base64 图像
const generateAndCacheBase64 = async (
    fetchFunction: () => Promise<Blob>,
    cacheKey: string,
    etagKey: string,
    id?: number
): Promise<string> => {
    if (!id) return '';
    
    try {
      // 尝试获取现有 ETag
      const existingEtag = sessionStorage.getItem(etagKey);
      
      // 添加 ETag 到请求头（如果存在）
      const headers = existingEtag ? { 'If-None-Match': existingEtag } : {};
      const blob = await fetchFunction(headers);
      
      // 检查是否返回了新的 ETag
      const newEtag = blob.headers?.get('ETag');
      if (newEtag) {
        sessionStorage.setItem(etagKey, newEtag);
      }
      
      // 转换为 Base64
      return new Promise<string>((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => {
          const base64Data = reader.result as string;
          sessionStorage.setItem(cacheKey, base64Data);
          resolve(base64Data);
        };
        reader.readAsDataURL(blob);
      });
    } catch (error) {
      if (error?.response?.status === 304) {
        // 资源未修改，使用缓存
        return sessionStorage.getItem(cacheKey) || '';
      }
      console.error(`获取资源失败: ${cacheKey}`, error);
      return '';
    }
};
  
// 获取资源 Base64（优先使用缓存）
const getResourceBase64 = async (
    fetchFunction: (headers?: Record<string, string>) => Promise<Blob>,
    cacheKey: string,
    etagKey: string,
    id?: number
  ): Promise<string> => {
    if (!id) return '';
    
    // 检查是否有有效缓存
    const cachedBase64 = sessionStorage.getItem(cacheKey);
    if (cachedBase64) {
      return cachedBase64;
    }
    
    // 没有缓存或需要更新
    return generateAndCacheBase64(fetchFunction, cacheKey, etagKey, id);
};
  
export async function getInitialState() {
    // 尝试从缓存读取菜单数据
    const cached = localStorage.getItem(CACHE_KEYS.MENU);
    let state: any = { 
      menuItems: [], 
      currentUser: {}, 
      systemConfig: {}, 
      permission:[],
      avatarUrl: '', 
      logoUrl: '' ,
      themeColor:'',
    };
  
    const token = getAccessToken();
    if (!token) {
      localStorage.removeItem(CACHE_KEYS.MENU);
      return state;
    }
  
    // 获取系统信息（如果有缓存则使用）
    if (cached) {
      try {
        state = JSON.parse(cached);
      } catch (e) {
        console.error('解析缓存数据失败', e);
        localStorage.removeItem(CACHE_KEYS.MENU);
      }
    }
    
    // 如果没有缓存或解析失败，重新获取系统信息
    if (!cached || !state.menuItems?.length) {
      try {
        const { data } = await getSystemInfo();
        state = {
          menuItems: data.menus || [],
          currentUser: data.user || {},
          systemConfig: data.systemConfig || {},
          permission: data.buttons || {},
        };
        localStorage.setItem(CACHE_KEYS.MENU, JSON.stringify(state));
      } catch (error) {
        console.error('初始化数据失败:', error);
      }
    }
  
    // 并行获取头像和 logo（使用缓存优先策略）
    try {
      const [avatarUrl, logoUrl] = await Promise.all([
        getResourceBase64(
          (headers) => getUserAvatar(state.currentUser?.userId, headers),
          CACHE_KEYS.AVATAR,
          CACHE_KEYS.AVATAR_ETAG,
          state.currentUser?.userId
        ),
        getResourceBase64(
          (headers) => getSystemLogo(state.systemConfig?.id, headers),
          CACHE_KEYS.LOGO,
          CACHE_KEYS.LOGO_ETAG,
          state.systemConfig?.id
        )
      ]);
      
        // 从 localStorage 获取主题颜色
        const themeColor = localStorage.getItem('theme-color') || '#0089DC';
        return {
            ...state,
            avatarUrl,
            logoUrl,
            themeColor, // 添加主题颜色到初始状态
            // 添加全局方法
    openGlobalTab: (key: string, label: string, path: string, state?: any) => {
        if (typeof window !== 'undefined') {
          window.dispatchEvent(new CustomEvent('open-global-tab', {
            detail: { key, label, path, state }
          }));
        }
      },
      
      closeCurrentTab: (navigateTo?: string) => {
        if (typeof window !== 'undefined') {
          window.dispatchEvent(new CustomEvent('close-current-tab', {
            detail: { navigateTo }
          }));
        }
      }
        };
    } catch (error) {
      console.error('获取头像或 logo 失败:', error);
      return state;
    }
}

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    pure: true,
    children: <CustomLayout />
  };
};

// 安全打印路由信息函数
function logRoutes(routes: any, indent = 0) {
  const indentStr = ' '.repeat(indent * 2);
  
  if (Array.isArray(routes)) {
    routes.forEach((route, index) => {
      console.log(`${indentStr}${index + 1}. ${route.id || 'no-id'}: ${route.path || 'no-path'} [${route.name || 'no-name'}]`);
      if (route.routes) {
        console.log(`${indentStr}  ↳ 子路由:`);
        logRoutes(route.routes, indent + 2);
      }
    });
  } else if (typeof routes === 'object' && routes !== null) {
    Object.entries(routes).forEach(([key, route]: [string, any]) => {
      console.log(`${indentStr}${key}: ${route.id || 'no-id'}: ${route.path || 'no-path'} [${route.name || 'no-name'}]`);
      if (route.routes) {
        console.log(`${indentStr}  ↳ 子路由:`);
        logRoutes(route.routes, indent + 2);
      }
    });
  }
}

// 从菜单生成路由 - 支持多层级嵌套
function generateRoutesFromMenus(menus: MenuItem[]): any[] {
  const routes: any[] = [];
  
  // 递归处理菜单项 - 只处理有有效 path 的叶子节点
  const processMenu = (menu: MenuItem) => {
    // 只处理有有效 path 的菜单项
    if (menu.path && menu.path.trim() !== '') {
      const normalizedPath = normalizePath(menu.path);
      const routeId = `dynamic-${menu.menuId}`;
      
      // 使用 Umi v4 兼容的方式动态加载组件
      const LazyComponent = React.lazy(async () => {
          try {
            const module = await import(/* @vite-ignore */ `@/pages${normalizedPath}`);
            return { default: module.default };
          } catch (e) {
          }
        // 所有尝试失败，返回404组件
        console.error(`无法加载组件: ${normalizedPath}`);
        try {
          const { default: NotFound } = await import('@/pages/404');
          return { default: NotFound };
        } catch (e) {
          return { 
            default: () => <div style={{ padding: 24 }}>页面加载失败: {normalizedPath}</div> 
          };
        }
      });
      
      routes.push({
        id: routeId,
        path: normalizedPath,
        name: menu.name,
        // 关键修复：移除 exact，使用 Umi 4 的匹配规则
        element: (
          <React.Suspense fallback={<div style={{ padding: 24, textAlign: 'center' }}>加载中...</div>}>
            <LazyComponent />
          </React.Suspense>
        ),
      });
    }
    
    // 递归处理子菜单
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => {
        // 确保子菜单存在且非空
        if (child) {
          processMenu(child);
        }
      });
    }
  };
  
  // 处理所有顶级菜单及其子菜单
  menus.forEach(menu => {
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => {
        processMenu(child);
      });
    } else {
      // 处理没有子菜单的顶级菜单项
      processMenu(menu);
    }
  });
  
  return routes;
}

// Umi 4兼容的动态路由注入
export function patchClientRoutes({ routes }: { routes: any }) {
  // 只在客户端执行
  if (typeof window === 'undefined') return;
  try {
    const cachedState = JSON.parse(localStorage.getItem('menu-cache') || '{}');
    const { menuItems = [] } = cachedState;
    // 未登录或菜单数据为空时跳过注入
    const token = getAccessToken();
    if (!token || !cachedState?.menuItems?.length) {
    //   console.log('[路由拦截] 未登录或菜单数据为空');
      history.push(LOGIN_PATH);
      return;
    }
    console.log('=== 开始注入动态路由 ===');
    // console.log('原始路由结构:',routes);
    // logRoutes(routes);
    // 1. 查找自定义布局路由 (id=2)
    let customLayoutRoute: any = null;
    // 递归查找函数
    const findRoute = (routeList: any): any => {
      if (Array.isArray(routeList)) {
        for (const route of routeList) {
          if (route.id === '2') return route;
          if (route.routes) {
            const found = findRoute(route.routes);
            if (found) return found;
          }
        }
      } else if (typeof routeList === 'object' && routeList !== null) {
        for (const key in routeList) {
          const route = routeList[key];
          if (route.id === '2') return route;
          if (route.routes) {
            const found = findRoute(route.routes);
            if (found) return found;
          }
        }
      }
      return null;
    };
    customLayoutRoute = findRoute(routes);
    if (!customLayoutRoute) {
      console.error('自定义布局路由 (id=2) 未找到');
      return;
    }
    console.log('找到自定义布局路由:', customLayoutRoute);
    // 2. 确保有routes数组
    if (!customLayoutRoute.routes) {
      customLayoutRoute.routes = [];
    } else if (!Array.isArray(customLayoutRoute.routes)) {
      // 如果routes是对象，转换为数组
      customLayoutRoute.routes = Object.values(customLayoutRoute.routes);
    }
    // 3. 从菜单生成实际路由
    const dynamicRoutes = generateRoutesFromMenus(menuItems);
    // console.log('生成的动态路由:', dynamicRoutes.map(r => ({
    //   id: r.id,
    //   path: r.path,
    //   name: r.name
    // })));
    // 4. 添加到自定义布局路由的routes中
    // 在404路由前插入
    const notFoundIndex = customLayoutRoute.routes.findIndex(
      (r: any) => r.id === '5'
    );
    if (notFoundIndex >= 0) {
      customLayoutRoute.routes.splice(notFoundIndex, 0, ...dynamicRoutes);
    } else {
      customLayoutRoute.routes.push(...dynamicRoutes);
    }
    // console.log('修改后的路由结构:');
    // logRoutes(routes);
    // 5. 打印所有路由路径以便调试
    // const allPaths: string[] = [];
    // const collectPaths = (routeList: any) => {
    //   if (Array.isArray(routeList)) {
    //     routeList.forEach(route => {
    //       if (route.path) allPaths.push(route.path);
    //       if (route.routes) collectPaths(route.routes);
    //     });
    //   } else if (typeof routeList === 'object' && routeList !== null) {
    //     Object.values(routeList).forEach((route: any) => {
    //       if (route.path) allPaths.push(route.path);
    //       if (route.routes) collectPaths(route.routes);
    //     });
    //   }
    // };
    
    // collectPaths(routes);
    // console.log('所有已注册的路由路径:', allPaths);
    
    // console.log(`✅ 成功添加 ${dynamicRoutes.length} 个动态路由`);
    
    //注册路由到 Umi 路由表
    dynamicRoutes.forEach(route => {
      window.g_routes = window.g_routes || {};
      window.g_routes[route.id] = {
        ...route,
        // Umi 需要这些额外的字段
        parentId: customLayoutRoute.id,
        file: `dynamic:${route.path}`,
      };
    });
    
  } catch (error) {
    console.error('❌ 动态路由添加失败:', error);
  }
}
  

// 路由变化监听器 - 增强调试
export function onRouteChange({ location, routes, matchedRoutes }: any) {
//   if (!matchedRoutes || matchedRoutes.length === 0) {
//     console.warn('警告：没有匹配的路由！');
//     // 尝试手动匹配路由
//     const findMatchingRoute = (routeList: any, path: string): any => {
//       if (Array.isArray(routeList)) {
//         for (const route of routeList) {
//           if (route.path === path) return route;
//           if (route.routes) {
//             const found = findMatchingRoute(route.routes, path);
//             if (found) return found;
//           }
//         }
//       } else if (typeof routeList === 'object' && routeList !== null) {
//         for (const key in routeList) {
//           const route = routeList[key];
//           if (route.path === path) return route;
//           if (route.routes) {
//             const found = findMatchingRoute(route.routes, path);
//             if (found) return found;
//           }
//         }
//       }
//       return null;
//     };
//     const matchedRoute = findMatchingRoute(routes, location.pathname);
//     if (matchedRoute) {
//       console.warn('手动找到匹配的路由:', matchedRoute);
//     } else {
//       console.warn('手动匹配也失败，可能路径未正确注册');
//     }
//   } else {
//     console.log('匹配的路由:', matchedRoutes.map((r: any) => r.path));
//   }
  
// //   打印匹配的路由
//   try {
//     console.log('完整路由结构:');
//      logRoutes(routes);
//   } catch (e) {
//     console.warn('路由打印失败:', e);
//   }
}

export function render(oldRender: any) {
    // 恢复活动选项卡
    const activeTabKey = getActiveTabKey();
    
    if (activeTabKey) {
      // 只恢复不在菜单中的页面状态
      if (!activeTabKey.startsWith('menu_') && !activeTabKey.startsWith('static_')) {
        const state = getTabState(activeTabKey);
        if (state) {
          // 检查当前路径是否匹配
          const currentPath = window.location.pathname;
          const tabPanes = JSON.parse(sessionStorage.getItem('tabPanes') || []);
          const tab = tabPanes.find((t: any) => t.key === activeTabKey);
          
          // 确保路径匹配时才恢复状态
          if (tab && tab.path === currentPath) {
            history.replace(currentPath, {
              ...history.location.state,
              ...state,
              _recovered: true
            });
          }
        }
      }
    }
    
    oldRender();
  }
  

// 请求配置
export const request = {
  prefix: isDev ? '/api-proxy' : '',
  ...errorConfig,
  requestInterceptors: [
    (url: any, options: { headers: any }) => {
    //   console.log(options)
      const headers = options.headers ? options.headers : {};
      const authHeader = headers['Authorization'];
      const isToken = headers['isToken'];
      if (!authHeader && isToken !== false) {
        const expireTime = getTokenExpireTime();
        if (expireTime) {
          const left = Number(expireTime) - new Date().getTime();
          const refreshToken = getRefreshToken();
          if (left < 5 * 60 * 1000 && refreshToken) {
            if (left < 0) {
              clearSessionToken();
            }
          } else {
            const accessToken = getAccessToken();
            if (accessToken) {
              headers['Authorization'] = `Bearer ${accessToken}`;
            }
          }
        } else {
          clearSessionToken();
        }
      }
      const finalUrl = `${options.prefix}${url}`;
      return { url: finalUrl, options };
    },
  ],
  responseInterceptors: [
    (response: any) =>
    {
      const { data = {} as any, config } = response;
      if(data && (data.code==1006 || data.code==1007 || data.code==1008)){
        clearSessionToken();
        notification.warning({
            message: '登录失效',
            description: '您的登录已过期，请重新登录',
            placement: 'topRight',
            duration: 3,
          });
        history.push(LOGIN_PATH);
      }

      let token = response?response.headers.authorization:"";
      if(token){
        const current = new Date();
        const expireTime = current.setTime(current.getTime() + 1000 * 12 * 60 * 60);
        setSessionToken(token, token, expireTime);
      }
    //   console.log(response)
      return response
    },
  ],
};
